from rest_framework.exceptions import NotFound
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet

from book.models import BookInfo
from book.serializers_2 import BookSerializer


class BooksViewSet(ViewSet):

    def list(self, request):
        books = BookInfo.objects.all()
        ser = BookSerializer(books, many=True)
        return Response(ser.data)

    def create(self, request):
        book = BookSerializer(data=request.data)
        book.is_valid(raise_exception=True)
        book.save()
        return Response(book.data)


class BookViewSet(ViewSet):

    def retrieve(self, request, pk):
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            raise NotFound
        book = BookSerializer(book)
        return Response(book.data)


    def update(self, request, pk):
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            raise NotFound
        serializer = BookSerializer(book, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.validated_data)

    def destroy(self, request, pk):
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            raise NotFound

        BookInfo.objects.filter(id=pk).delete()

        return Response('删除成功')
